package com.eduction.controller;

import com.eduction.bean.ExpertGroupMapBean;
import com.eduction.bean.SessionUser;
import com.eduction.common.Hash;
import com.eduction.common.ReturnCode;
import com.eduction.modules.system.entity.Expert;
import com.eduction.modules.system.entity.OrgUserEntity;
import com.eduction.modules.system.entity.School;
import com.eduction.modules.system.entity.SysValue;
import com.eduction.resource.BaseController;
import com.eduction.service.IOrgUserService;
import com.eduction.service.ISysValueService;
import com.eduction.service.ObservationService;
import com.eduction.service.SchoolService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "/sys")
public class ServiceController extends BaseController {

    private Logger logger = Logger.getLogger(ServiceController.class);

    @Autowired
    private ISysValueService iSysValueService;
    @Autowired
    private SchoolService schoolService;
    @Autowired
    private IOrgUserService orgUserService;
    @Autowired
    private ObservationService observationService;

    /**
     * 学校登录
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/schoolLogin", produces = MediaType.TEXT_HTML_VALUE + ";charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> login(HttpServletRequest request,
                                        HttpServletResponse response,
                                        @RequestBody Map<String, String> map
    ) {
        try {
            String account = map.get("account");
            if (StringUtils.isBlank(account)) {
                return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "account不可为空");
            }
            String password = map.get("password");
            if (StringUtils.isBlank(password)) {
                return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "password不可为空");
            }

            SysValue asv = iSysValueService.getSysValue("1001001"); //专业设置
            if (asv == null)
                return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "当前不是申报阶段");
            else {
                if (!"1001".equals(asv.getSysvalue()))
                    return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "当前不是申报阶段");
            }

            School a = schoolService.querySchoolByAccount(account);
            if (null == a) {
                return toResponse(null, ReturnCode.USERNAME_OR_PASSWORD_FALSE, "用户名或密码错误");
            }
//            String newPassw = Hash.sha2InHex(password);
            String newPassw =password;
            if (!newPassw.equals(a.getP_password())) {
                return toResponse(null, ReturnCode.USERNAME_OR_PASSWORD_FALSE, "用户名或密码错误");
            }

            request.getSession().setAttribute(SessionUser.SESSION_USER_TYPE, "0");
            request.getSession().setAttribute(SessionUser.SESSION_USER_KEY, a.getP_id());

            request.getSession().setAttribute(SessionUser.SCHOOL_TYPE, a.getP_type_id());


            request.getSession().setMaxInactiveInterval(1800);

            Map<String, String> m = new HashMap<String, String>();

            m.put("userId", a.getP_id());
            m.put("schoolName", a.getS_name());
            m.put("type", a.getP_type_id());
            return toResponse(m, ReturnCode.SUCCESS, "登录验证成功");
        } catch (Exception e) {
            logger.error("登录异常", e);
            return toResponse(null, ReturnCode.FAIL, "登录异常");
        }
    }

    /**
     * 管理员登录
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/adminLogin", produces = MediaType.TEXT_HTML_VALUE + ";charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> adminLogin(HttpServletRequest request,
                                             HttpServletResponse response,
                                             @RequestBody Map<String, String> map
    ) {
        try {
            String account = map.get("account");
            if (StringUtils.isBlank(account)) {
                return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "account不可为空");
            }
            String password = map.get("password");
            if (StringUtils.isBlank(password)) {
                return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "password不可为空");
            }
            OrgUserEntity s = orgUserService.getAuthOrgUserByAccount(account, "1");
            if (null == s) {
                return toResponse(null, ReturnCode.USERINFO_NOT_EXIST, "管理员帐号或密码错误");
            }
//            String newPassw = Hash.sha2InHex(password);
            String newPassw = password;
            if (!newPassw.equals(s.getS_password())) {
                return toResponse(null, ReturnCode.USERNAME_OR_PASSWORD_FALSE, "管理员帐号或密码错误");
            }
            Map<String, String> m = new HashMap<String, String>();
            m.put("account", s.getP_id());
            m.put("type", s.getS_type());

            request.getSession().setAttribute(SessionUser.SESSION_USER_TYPE, "4");//管理员
            request.getSession().setAttribute(SessionUser.SESSION_USER_KEY, s.getP_id());
            request.getSession().setMaxInactiveInterval(1800);

            return toResponse(m, ReturnCode.SUCCESS, "登录验证成功");
        } catch (Exception e) {
            logger.error("登录异常", e);
            return toResponse(null, ReturnCode.FAIL, "登录异常");
        }
    }

    /**
     * 专家用户登录（现场考察）
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/expertLogin_review", produces = MediaType.TEXT_HTML_VALUE + ";charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> exportLogin(HttpServletRequest request, HttpServletResponse response,
                                              @RequestBody Map<String, String> map
    ) {
        try {
            String account = map.get("account");
            if (StringUtils.isBlank(account)) {
                return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "account不可为空");
            }
            String password = map.get("password");
            if (StringUtils.isBlank(password)) {
                return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "password不可为空");
            }
            Expert ae = observationService.queryExpertByAccount(account);
            if (null == ae) {
                return toResponse(null, ReturnCode.USERNAME_OR_PASSWORD_FALSE, "用户名或密码错误");
            }
//            String newPassw = Hash.sha2InHex(password);
            String newPassw = password;
            if (!newPassw.equals(ae.getS_password())) {
                return toResponse(null, ReturnCode.USERNAME_OR_PASSWORD_FALSE, "用户名或密码错误");
            }
            SysValue asv = iSysValueService.getSysValue("1001001");
            String userType = map.get("user_type");
//			String userType="2";
            if ("1".equals(userType)) {
                if (!"1002".equals(asv.getSysvalue())) {
                    return toResponse(null, ReturnCode.AUTH_PHASE_IS_FALSE, "当前非材料评审阶段");
                }
            } else if ("2".equals(userType)) {
                if (!"1004".equals(asv.getSysvalue())) {
                    return toResponse(null, ReturnCode.AUTH_PHASE_IS_FALSE, "当前非现场考察阶段");
                }
            }
            ExpertGroupMapBean a = observationService.queryExpertGroupMap(ae.getPid());
//            if (null == a || !"1".equals(ae.getS_strutss())) {
//                return toResponse(null, ReturnCode.USER_IDENTITY_NOT_MATCH, "非该阶段专家不可登录该系统");
//            }
             if (null == a ) {
                return toResponse(null, ReturnCode.USER_IDENTITY_NOT_MATCH, "非该阶段专家不可登录该系统");
            }
            request.getSession().setAttribute(SessionUser.SESSION_USER_TYPE, userType);//现场考察专家组成员
            request.getSession().setAttribute(SessionUser.SESSION_USER_KEY, ae.getPid());
            request.getSession().setAttribute(SessionUser.IDENTITY, a.getS_identity());//1:组员  2：组长 3：联络员
            request.getSession().setMaxInactiveInterval(1800);

            Map<String, String> m = new HashMap<String, String>();
            m.put("userId", ae.getPid());
            m.put("userType", userType);//1，材料评审专家，2.现场考察专家
            m.put("expertName", ae.getS_name());//现场考察名字
            m.put("account", ae.getS_expert_code());//现场考察账号
            m.put("identity", a.getS_identity());//1:组员  2：组长 3：联络员

            return toResponse(m, ReturnCode.SUCCESS, "登录验证成功");
        } catch (Exception e) {
            logger.error("登录异常", e);
            return toResponse(null, ReturnCode.FAIL, "登录异常");
        }
    }

//	/**
//	 * 专家用户登录（材料评审）
//	 * @param map
//	 * @return
//	 */
//	@RequestMapping(value="/expertLogin_review2" ,produces = MediaType.TEXT_HTML_VALUE+";charset=UTF-8", method=RequestMethod.POST)
//	@ResponseBody
//	public ResponseEntity<String> exportLogin2(HttpServletRequest request,HttpServletResponse response ,
//											  @RequestBody Map<String ,String> map
//	){
//		try {
//			String account=map.get("account");
//			if(StringUtils.isBlank(account)){
//				return toResponse(null,ReturnCode.PARAMETER_NOT_NULL,"account不可为空");
//			}
//			String password=map.get("password");
//			if(StringUtils.isBlank(password)){
//				return toResponse(null,ReturnCode.PARAMETER_NOT_NULL,"password不可为空");
//			}
//			Expert ae = observationService.queryExpertByAccount(account);
//			if(null==ae){
//				return toResponse(null,ReturnCode.USERNAME_OR_PASSWORD_FALSE,"用户名不存在");
//			}
//			String newPassw=Hash.sha2InHex(password);
//			if(!newPassw.equals(ae.getS_password())){
//				return toResponse(null,ReturnCode.USERNAME_OR_PASSWORD_FALSE,"用户名或密码错误");
//			}
//			SysValue asv = iSysValueService.getSysValue("1001001");
//			if(!"1004".equals(asv.getSysvalue())){
//				return toResponse(null,ReturnCode.AUTH_PHASE_IS_FALSE,"当前非材料评审阶段");
//			}
//			ExpertGroupMapBean a = observationService.queryExpertGroupMap(ae.getPid());
//			if(null == a || !"1".equals(ae.getS_strutss())){
//				return toResponse(null,ReturnCode.USER_IDENTITY_NOT_MATCH,"非材料评审专家不可登录该系统");
//			}
//
//			request.getSession().setAttribute(SessionUser.SESSION_USER_TYPE, "1");//材料评审专家组成员
//			request.getSession().setAttribute(SessionUser.SESSION_USER_KEY, ae.getPid());
//			request.getSession().setMaxInactiveInterval(1800);
//
//			Map<String,String> m=new HashMap<String, String>();
//			m.put("userId", ae.getPid());
//			m.put("userType", "1");//材料评审专家
//			m.put("expertName", ae.getS_name());//材料评审名字
//			m.put("account", ae.getS_expert_code());//材料评审专家账号
//			m.put("identity", a.getS_identity());//0：组员   1：副组长  2：组长 3：联络员
//
//			return toResponse(m,ReturnCode.SUCCESS,"登录验证成功");
//		} catch (Exception e) {
//			logger.error("登录异常", e);
//			return toResponse(null,ReturnCode.FAIL,"登录异常");
//		}
//	}

    /**
     * 修改密码
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/updatePassword", produces = MediaType.TEXT_HTML_VALUE + ";charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> updatePassword(HttpServletRequest request,
                                                 HttpServletResponse response,
                                                 @RequestBody Map<String, String> map
    ) {
        try {
            ////0 机构  1：材料评审员 2：现场考察员  3：超级管理员 4 ：系统管理员
           String  type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
            if(StringUtils.isEmpty(type)){
                return toResponse(null,ReturnCode.FAIL,"暂无权限！");
            }
            String account = map.get("account");
            if (StringUtils.isBlank(account)) {
                return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "account不可为空");
            }
            String password = map.get("password");
            String newPassword = map.get("newPassword");
            if (StringUtils.isBlank(password)) {
                return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "旧密码不可为空");
            }
            if (StringUtils.isBlank(newPassword)) {
                return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "新密码不可为空");
            }
            if ("0".equals(type)) {
                School a = schoolService.querySchoolByAccount(account);
                if (null == a) {
                    return toResponse(null, ReturnCode.USERNAME_OR_PASSWORD_FALSE, "用户名或密码错误");
                }
                String newPassw = Hash.sha2InHex(password);
                if (!newPassw.equals(a.getP_password())) {
                    return toResponse(null, ReturnCode.USERNAME_OR_PASSWORD_FALSE, "用户名或密码错误");
                }
                String newPassw2 = Hash.sha2InHex(newPassword);
                a.setP_password(newPassw2);
                schoolService.resetPassword(a.getP_id(),a.getP_password());
//                schoolService.saveSchool(a);
            } else if ("1".equals(type) || "2".equals(type)) {
                Expert ae = observationService.queryExpertByAccount(account);
                if (null == ae) {
                    return toResponse(null, ReturnCode.USERNAME_OR_PASSWORD_FALSE, "用户名或密码错误");
                }
                String newPassw = Hash.sha2InHex(password);
                if (!newPassw.equals(ae.getS_password())) {
                    return toResponse(null, ReturnCode.USERNAME_OR_PASSWORD_FALSE, "用户名或密码错误");
                }
                String newPassw2 = Hash.sha2InHex(newPassword);
                ae.setS_password(newPassw2);
                observationService.saveExpertInfo(ae);
            } else if ("4".equals(type)) {
                OrgUserEntity s = orgUserService.getAuthOrgUserByAccount(account, "1");
                if (null == s) {
                    return toResponse(null, ReturnCode.USERINFO_NOT_EXIST, "管理员信息不存在");
                }
                String newPassw = Hash.sha2InHex(password);
                if (!newPassw.equals(s.getS_password())) {
                    return toResponse(null, ReturnCode.USERNAME_OR_PASSWORD_FALSE, "密码错误");
                }
                String newPassw2 = Hash.sha2InHex(newPassword);
                s.setS_password(newPassw2);
                orgUserService.saveAuthOrgUserInfo(s);
            }

            return toResponse(null, ReturnCode.SUCCESS, "修改密码成功");
        } catch (Exception e) {
            logger.error("修改密码异常", e);
            return toResponse(null, ReturnCode.FAIL, "修改密码异常");
        }
    }

    /**
     * 重置密码
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/resetPassword", produces = MediaType.TEXT_HTML_VALUE + ";charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> resetPassword(HttpServletRequest request,
                                                HttpServletResponse response,
                                                @RequestBody Map<String, String> map
    ) {
        try {
            String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
            if(StringUtils.isEmpty(user_type)){
                return toResponse(null,ReturnCode.FAIL,"暂无权限！");
            }

            ////0 机构  1：材料评审员 2：现场考察员  3：超级管理员 4 ：系统管理员
            String type = map.get("type");
            String account = map.get("account");
            if (StringUtils.isBlank(account)) {
                return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "account不可为空");
            }

            if ("0".equals(type)) {
                School a = schoolService.querySchoolByAccount(account);
                if (null == a) {
                    return toResponse(null, ReturnCode.USERNAME_OR_PASSWORD_FALSE, "用户名或密码错误");
                }
                String newPassw = Hash.sha2InHex("111111");
                a.setP_password(newPassw);

                schoolService.resetPassword(a.getP_id(),a.getP_password());
//                schoolService.saveSchool(a);
            } else if ("1".equals(type) || "2".equals(type)) {
                Expert ae = observationService.queryExpertByAccount(account);
                if (null == ae) {
                    return toResponse(null, ReturnCode.USERNAME_OR_PASSWORD_FALSE, "管理员帐号或密码错误");
                }
                String newPassw = Hash.sha2InHex("111111");
                ae.setS_password(newPassw);
                observationService.saveExpertInfo(ae);
            } else if ("4".equals(type)) {
                OrgUserEntity s = orgUserService.getAuthOrgUserByAccount(account, "1");
                if (null == s) {
                    return toResponse(null, ReturnCode.USERINFO_NOT_EXIST, "管理员帐号或密码错误");
                }
                String newPassw = Hash.sha2InHex("111111");
                s.setS_password(newPassw);
                orgUserService.saveAuthOrgUserInfo(s);
            }
            return toResponse(null, ReturnCode.SUCCESS, "重置密码成功");
        } catch (Exception e) {
            logger.error("重置密码异常", e);
            return toResponse(null, ReturnCode.FAIL, "重置密码异常");
        }
    }


    @RequestMapping(value = "logout", produces = MediaType.TEXT_HTML_VALUE + ";charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public String logout(HttpServletRequest request){
        String pid=(String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
        if(null!=pid){
            request.getSession().removeAttribute(SessionUser.SESSION_USER_KEY);
            request.getSession().invalidate();
        }
        return "1";
    }

}
